package com.kingsoft.miot.bridge.iam.group;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kingsoft.miot.bridge.exception.CommonException;
import com.kingsoft.miot.bridge.iam.common.AwsSignerV4Util;

/**
 * 组操作
 * 
 * @author HUJIANQING
 *
 */
public class GroupOption {

	private static final Logger LOGGER = LoggerFactory.getLogger(GroupOption.class);

	// 请求测试系统
	private static final String API = "http://iam.api.ksyun.com/";
	// 服务名
	private static String SERVICE = "iam";
	// 区域
	private static String REGION = "cn-beijing-6";
	// ak sk
	private static String AK = "AKLTuJudK0klRmiH6gNWiXkFlA";
	private static String SK = "OBcrjHtdjbNsBB++Rl3MkdgoNQ/26jpGqkGe91PbgZeTNk7Rwbk7J1u0VGoBH5DDDg==";

	/**
	 * 附加用户到用户组中
	 * 
	 * @param groupName 组名称
	 * @param userName  用户名称
	 */
	public static void addUserToGroup(String groupName, String userName) {
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("Action", "AddUserToGroup");
		parameters.put("Version", "2015-11-01");
		parameters.put("Path", "/");
		parameters.put("GroupName", groupName);
		parameters.put("UserName", userName);
		parameters.put("AccountId", "2000090910");
		doGetRequest(parameters);
	}

	/**
	 * 添加多个用户到用户组
	 * 
	 * @param groupName
	 * @param userNameList
	 */
	public static void addUserListToGroup(String groupName, List<String> userNameList) {
		if (CollectionUtils.isEmpty(userNameList)) {
			throw new CommonException("用户名称为空。");
		}
		for (String userName : userNameList) {
			addUserToGroup(groupName, userName);
		}
	}
	
	/**
	 * 附加策略到用户组
	 * 
	 * @param groupName
	 * @param PolicyKrn
	 */
	public static void attachGroupPolicy(String groupName,String policyKrn) {
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("Action", "AttachGroupPolicy");
		parameters.put("Version", "2015-11-01");
		parameters.put("Path", "/");
		parameters.put("GroupName", groupName);
		parameters.put("PolicyKrn", policyKrn);
		parameters.put("AccountId", "2000090910");
		doGetRequest(parameters);
	}
	

	/**
	 * 发送get请求
	 * 
	 * @param parameters
	 * @return
	 */
	private static String doGetRequest(Map<String, String> parameters) {
		StringBuffer response = new StringBuffer();
		try {
			URI uri = new URI(API);
			String query = "?";
			for (Map.Entry<String, String> entry : parameters.entrySet()) {
				query = query + entry.getKey() + '=' + entry.getValue() + '&';
			}
			query = query.substring(0, query.length() - 1);
			// 获取get认证
			Map<String, String> h = AwsSignerV4Util.getAuthHeaderForGet(uri, parameters, null, SERVICE, REGION, AK, SK);
			System.out.println(query);
			URL url = new URL(API + query);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("GET");
			// add request header
			conn.setRequestProperty("Accept", "application/json");
			for (Map.Entry<String, String> entry : h.entrySet()) {
				System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}
			int responseCode = conn.getResponseCode();
			LOGGER.info("发送请求到 : " + url);
			LOGGER.info("响应码 : " + responseCode);
			// Reading response from input Stream
			BufferedReader in;
			if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
				in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			} else {
				in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
			}
			String output;
			while ((output = in.readLine()) != null) {
				response.append(output);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// printing result from response
//		System.out.println(response.toString());
		return response.toString();
	}

	public static void main(String[] args) {
		addUserToGroup("ChiefManager", "hujianqing");
		addUserToGroup("ChiefManager", "xiaojiang");
	}

}
